function item(it, name, x, y) {
    it.left = x;
    it.top = y;
    var div = document.createElement('div');
    div.innerHTML = name;
    div.style.top = y + 'px';
    div.style.left = x + 'px';
    div.className = 'item';
    document.getElementById('result').appendChild(div);
}

function border(source, target) {
    var div = document.createElement('div');
    div.className = 'border';
    div.style.width = Math.max(1, Math.abs(source.left - target.left) - itemWidth / 2 + letter / 2) + 'px';
    div.style.height = (Math.abs(source.top - target.top) - rowHeight / 2) + 'px';
    if (source.left < target.left) {
        div.style.borderTopWidth = '1px';
        div.style.borderLeftWidth = '1px';
        div.style.left = (source.left + itemWidth / 2 - letter / 2) + 'px';
        div.style.top = (target.top + rowHeight / 2) + 'px';
    }
    if (source.left === target.left) {
        div.style.borderLeftWidth = '1px';
        div.style.left = (source.left + itemWidth / 2 - letter / 2) + 'px';
        div.style.top = Math.abs(source.top - letter) + 'px';
        div.style.height = letter + 'px';
    }
    if (source.left > target.left) {
        div.style.borderTopWidth = '1px';
        div.style.borderRightWidth = '1px';
        div.style.left = (target.left + itemWidth - letter) + 'px';
        div.style.top = (target.top + rowHeight / 2) + 'px';
    }

    document.getElementById('result').appendChild(div);
}

var leafWidth = 50;
var letter = 10;
var itemWidth = leafWidth + letter;
var rowHeight = 100 + letter;
document.getElementById('result').innerHtml = '';

export function cal(list, left) {
    var reduce = 0;
    list.forEach((it, index) => {
        if (it.children && it.children.length) {
            left = Math.max(reduce, cal(it.children, left + 1));
            it.column = Math.max(left, it.column || 0);
        } else {
            it.column = left + index;
            console.log(it.level, it.index, left, it.column);
        }

        reduce = Math.max(it.column, reduce);
    });

    return reduce;
}

export function render(data, parent) {
    data.forEach(it => {
        if (it.children && it.children.length > 1) {
            var min = 999999;
            var max = 0;
            it.children.forEach(child => {
                min = Math.min(child.column, min);
                max = Math.max(child.column, max);
            });
            var center = min * itemWidth + (max - min) * itemWidth / 2;
            item(it, 'r' + it.level + it.index, center, it.level * rowHeight);
        } else {
            item(it, 'r' + it.level + it.index, it.column * itemWidth, it.level * rowHeight);
        }

        if (parent) {
            border(it, parent);
        }

        render(it.children, it);
    });
}

